google.load("jquery", "1");
google.load("jqueryui", "1");
google.setOnLoadCallback(function() {
    $("button").button();
    $(".project-summary").hover(
            function() {
                $(this).addClass("ui-state-highlight");
            },
            function() {
                $(this).removeClass("ui-state-highlight");
            }
    );

    // planner
    $('#planner-wrapper').slideUp();
    $('#show-add-test-case').click(CreateTestCaseDialog.show);

    // dashboard tool bar
    $('#projects-wrapper-title').click(switchToProjectView);
    $('#create-project').click(CreateProjectDialog.open);
    $('#add-test-plan').click(onAddTestPlanClicked).addClass('ui-state-disabled').attr('disabled', 'disabled');

    // dialog
    CreateTestPlanDialog.initialize();
    CreateProjectDialog.initialize();
    CreateTestCaseDialog.initialize();

    // logical computation
    main();
});


function switchToProjectView(event)
{
    $('#planner-wrapper').slideUp(function() { $('#projects-wrapper').slideDown(); });

    return false;
}


/**
 * Client-side project class.
 */

function Project_onProjectNameClicked(event)
{
    var projectName = $(event.target).text();
    alert(projectName);
    return false;
}

function Project_onProjectClicked(event)
{
    $('.project-summary').removeClass('ui-state-highlight');
    $(event.target).closest('.project-summary').addClass('ui-state-highlight');
    $('#add-test-plan').removeClass('ui-state-disabled').removeAttr('disabled');
    return false;
}

function Project_onPlanClicked(event)
{
    var planKey = $(event.target).data('key');
    var planName = $(event.target).text();
    $('#planner-wrapper h3').text('Plan ' + planName + '[' + planKey + ']');
    $('#new-test-case-plan').attr('value', planKey);

    // load test cases
    $.getJSON('/action/testplan', { action: 'getCases', plan: planKey }, function(json)
    {
        // load data to dom
        var listRoot = $('<ul>');
        $.each(json.testCases, function(index, testCase)
        {
            $('<li>',
            {
                text: testCase.title,
                title: testCase.description
            }).data('info', testCase).appendTo(listRoot);
        });
        $('#planner-test-case-wrapper').empty().append(listRoot);

        // reveal
        CreateTestCaseDialog.close();
        $('#projects-wrapper').slideUp(function()
        {
            $('#planner-wrapper').slideDown();
        });
    });


    return false;
}

function Project(project)
{
    var that = this;
    this.name = project.name;
    this.description = project.description;
    var row = $('<tr>');

    // project release info
    project.releases.sort(function(r1, r2){
        return r1.name > r2.name ? 1 : -1;
    });
    var releaseNode = $('<ul>').addClass("project-release");
    $.each(project.releases, function(index, release)
    {
        $('<li>', {
            text : release.name,
            id: 'release-' + release.key,
            class: 'release-status-' + release.status.toLowerCase()  + ' ui-state-default ui-corner-all'
        }).appendTo(releaseNode);
    });

    // assemble project info
    $("<td>").addClass("project-info")
              .append( $("<a>", { class:"project-name", href:"#", text:project.name, click:Project_onProjectNameClicked }))
              .append( $("<div>", { class:"project-about", text:project.description }))
              .append( releaseNode )
              .appendTo(row);

    // project plans info
    project.plans.sort(function(p1, p2) {
        return p1.name > p2.name ? 1 : -1;
    });
    var plansList = $("<ul>");
    $.each(project.plans, function(index, plan) {
        var listItem = $("<li>");
        $("<a>", {
            class: "plan-name",
            text:plan.name,
            title: plan.description,
            id: 'test-plan-' + plan.key,
            href: '#',
            click: Project_onPlanClicked
        }).appendTo(listItem).data('key', plan.key);
        $("<span>", { class: "plan-state", text:plan.rate + " %" }).appendTo(listItem);
        plansList.append(listItem);
    });

    $("<td>").addClass("plan-summary").append(plansList).appendTo(row);

    // assemble all
    this.dom = $("<table>").addClass("ui-corner-all ui-widget-content project-summary")
                           .append(row)
                           .click(Project_onProjectClicked)
                           .data('key', project.key)
                           .data('name', project.name)
                           .data('releases', project.releases)
                           .attr('id', 'project-' + project.key);
}



var CreateProjectDialog =
{
    open: function()
    {
        CreateProjectDialog.reset();
        $('#create-project-dialog').dialog('open');
    },

    initialize:function()
    {
        var dialogContent = $("<div>").append($("<label>", { 'for': 'create-project-name', text: 'Project name:' }))
                                      .append($("<input>", { 'type': 'text', id: 'create-project-name' , class:'ui-widget-content'}))
                                      .append($("<label>", { 'for': 'create-project-description', text: 'Project name:'}))
                                      .append($("<textarea>", { 'id': 'create-project-description', class:'ui-widget-content' }));
        $("<div>").attr("id", "create-project-dialog")
                .attr("title", "Create Project")
                .hide()
                .append(dialogContent)
                .appendTo($("body"))
                .dialog({
                    autoOpen: false,
                    height: 300,
                    width: 350,
                    modal: true,
                    buttons: {
                        'Create project' : CreateProjectDialog.onCreateProject,
                        'Cancel' : CreateProjectDialog.onClose
                    }
                });
    },

    reset: function()
    {
        $("#create-project-name").val('');
        $("#create-project-description").val('');
    },

    onCreateProject: function()
    {
        CreateProjectDialog.onClose();
        var name = $("#create-project-name").val();
        var desc = $("#create-project-description").val();
        $.post( '/action/project', { 'action' : 'create', 'name' : name, 'desc' : desc }, function(result) {
            loadProject();
        });
    },

    onClose: function()
    {
        $('#create-project-dialog').dialog('close');
    }
    
};

var CreateTestPlanDialog =
{
    initialize: function()
    {
        $('#create-test-plan-dialog').hide().dialog({
            autoOpen: false,
            height: 400,
            width: 500,
            modal: true,
            buttons: {
                'Save' : CreateTestPlanDialog.onSave,
                'Cancel' : CreateTestPlanDialog.onClose
            }
        });

    },

    onOpen: function(projectId)
    {
        var releaseListRoot = $('#new-test-plan-release').empty();
        var projectElement = $('#project-' + projectId);
        var releases = projectElement.data('releases');
        $.each(releases, function(index, releaseInfo) {
            $('<option>').text(releaseInfo.name).attr('value', releaseInfo.key).appendTo(releaseListRoot);
        });

        $('#create-test-plan-dialog input[name=project]').val(projectId);
        $('#new-test-plan-project').text(projectElement.data('name'));
        $('#new-test-plan-name').val('');
        $('#new-test-plan-desc').val('');
        $('#create-test-plan-dialog').data('projectId', projectId).dialog('open');
    },

    onSave: function()
    {
        $.ajax({
            type: 'POST',
            url:'/action/testplan',
            data: $('form#new-test-plan-form').serialize(),
            success: CreateTestPlanDialog.onCreateSuccess,
            error: CreateTestPlanDialog.onCreateError
        });
    },

    onCreateSuccess: function(data, text, xhr)
    {
        CreateTestPlanDialog.onClose();
    },

    onCreateError: function(xhr, text, error)
    {
        alert(text);        
    },

    onClose: function()
    {
        loadProject();
        $('#create-test-plan-dialog').dialog('close');
    }
};

var CreateTestCaseDialog =
{
    initialize : function()
    {
        CreateTestCaseDialog.close();
        $('#submit-new-test-case').click(CreateTestCaseDialog.submit);
        $('#cancel-new-test-case').click(CreateTestCaseDialog.close);
    },

    show : function()
    {
        $('#create-test-case-form textarea').val('');
        $('#create-test-case-form input[type=text]').val('');
        $('#create-test-case-wrapper').slideDown();
    },

    submit : function()
    {
        $.post('/action/testplan', $('#create-test-case-form').serialize(), function(text) {
            console.log(text);
        });
    },

    close : function()
    {
        $('#create-test-case-wrapper').slideUp().hide();
    }

};

function onAddTestPlanClicked(event)
{
    var selectedProject = $('.project-summary.ui-state-highlight');
    if(selectedProject.length == 1)
    {
        CreateTestPlanDialog.onOpen(selectedProject.data('key'));
    }
    else
    {
        alert("Please select a project first.");
    }
    return false;
}

function loadProject()
{
    $.getJSON('/action/project', { action: 'list' }, function(json) {
        $('.project-summary').remove();
        json.projects.sort(function(p1, p2){
            return p1.name > p2.name ? 1 : -1;
        });
        $.each(json.projects, function(index, project) {
            var p = new Project(project);
            $("#projects-wrapper").append(p.dom);
        });
    });
}

function loadSessionUser()
{
    $.getJSON('/action/user', { action: 'session' }, function(json) {
        if(json.login)
        {
            $('#user-session').text('Welcome ' + json.user.name);
        }
        else
        {
            $('#user-session').text('Please log in.');
        }
    });
}

function main()
{
    loadSessionUser();
    loadProject();
}